﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.User;
using Provenance.Write.Api.Application.Command.User;

namespace Provenance.Write.Api.Application.CommandHandler.User
{
    public class UpdatePermissionCommandHandler : IRequestHandler<UpdatePermissionCommand, ApiResult>
    {
        private readonly IPermissionRepository _permissionRepository;
        private readonly IRolePermissionRepository _rolePermissionRepository;
        private readonly ILogger<UpdatePermissionCommandHandler> _logger;
        private readonly IMapper _mapper;
        public UpdatePermissionCommandHandler(IPermissionRepository permissionRepository, IRolePermissionRepository rolePermissionRepository, ILogger<UpdatePermissionCommandHandler> logger, IMapper mapper)
        {
            _permissionRepository = permissionRepository;
            _rolePermissionRepository = rolePermissionRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(UpdatePermissionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _permissionRepository.GetAsync(x => x.PermissionId == request.PermissionId);
                obj = _mapper.Map(request, obj);
                await _permissionRepository.UpdateEntity(obj);
                return ApiResult.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting permission" + ex.Message);
                return ApiResult.Failure("Error deleting permission" + ex.Message);
            }
        }
    }
}
